package com.alter.global.base.article.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.alter.model.AfTag;
import com.alter.orm.hibernate.HibernateDao;

@Repository
public class AfTagDao extends HibernateDao<AfTag, String> {

    /**
     * 保存TAG,如果已经存在的话,count在原有基础之上+1, 
     * 
     * @param tag
     * @return {@link AfTag} session 中关联对象。 
     */
    public AfTag saveorupdate(AfTag tag) {
	AfTag dbtag = findUniqueBy("name", tag.getName());
	if (dbtag == null) {
	    tag.setCount(1);
	} else {
	    tag = dbtag;
	    tag.setCount(dbtag.getCount() + 1);
	}
	save(tag);
	return tag;
    }

    /**
     * 根据文章ID 来查询关联的tag
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<AfTag> getTags(String articleAid) {
	Assert.notNull(articleAid, "文章ID 不能为空。");
	Criteria criteria = getSession().createCriteria(entityClass);
	Criteria article = criteria.createCriteria("articles");
	article.add(Restrictions.eq("aid", articleAid));
	return criteria.list();
    }
    
    /**
     * 查看对应文章的tag
     * @param articleAid
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<AfTag> searchTagsByArticleAid(String articleAid){
	Criteria _criteria = getSession().createCriteria(AfTag.class);
	Criteria _arti_criteria = _criteria.createCriteria("articles");
	_arti_criteria.add(Restrictions.eq("aid", articleAid));
	return (List<AfTag>)_criteria.list();
    }

}
